﻿using BaoShouTang.DBModel;
using BaoShouTangServer.Models;
using BaoShouTangServer.Service;
using Newtonsoft.Json;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI.WebControls;
using UFIDA.U8.MomServiceCommon;
using UFIDA.U8.U8MOMAPIFramework;
using UFIDA.U8.U8APIFramework;
using UFIDA.U8.U8APIFramework.Meta;
using UFIDA.U8.U8APIFramework.Parameter;
using MSXML2;
using Microsoft.Ajax.Utilities;

namespace BaoShouTangServer.ApiServies
{
    public static class rdrecord10Service
    {
        public static bool 生成成品入库单(U8Login.clsLogin u8Login, List<Z_任务单实际产出> z_任务单实际投入List, ref string rdrecord11Id, ref string 材料出库单接口返回result)
        {
            //第二步：构造环境上下文对象，传入login，并按需设置其它上下文参数
            U8EnvContext envContext = new U8EnvContext();
            envContext.U8Login = u8Login;



            //第三步：设置API地址标识(Url)
            //当前API：添加新单据的地址标识为：U8API/MaterialOut/Add
            U8ApiAddress myApiAddress = new U8ApiAddress("U8API/ProductIn/Add");


            //第四步：构造APIBroker
            U8ApiBroker broker = new U8ApiBroker(myApiAddress, envContext);

            //第五步：API参数赋值

            //给普通参数sVouchType赋值。此参数的数据类型为System.String，此参数按值传递，表示单据类型：11
            broker.AssignNormalValue("sVouchType", "10");



            //给BO表头参数DomHead赋值，此BO参数的业务类型为材料出库单，属表头参数。BO参数均按引用传递
            //提示：给BO表头参数DomHead赋值有两种方法

            DataTable Dt_data = new DataTable();

            DbHelperSQL.connectionString = u8Login.UFDataConnstringForNet;
            StringBuilder strMsg = new StringBuilder();
            StringBuilder Strsql = new StringBuilder();

            //创建临时表
            string StrHeadName = "tempdb..RecordInQ" + Guid.NewGuid().ToString().Replace("-", "");
            string StrBodyName = "tempdb..RecordInsQ" + Guid.NewGuid().ToString().Replace("-", "");
            Strsql.Append(" select  top 0  * into " + StrHeadName + " from RecordInQ Where 1=1");
            Strsql.Append(" \n select  top 0  *  into " + StrBodyName + " from RecordInsQ Where 1=1");
            DbHelperSQL.ExecuteSql(Strsql.ToString());
            int id = (int)SnowFlakeSingle.Instance.NextId();
            int zpurRkdHead = 成品入库头赋值(StrHeadName, id, z_任务单实际投入List);
            int zpurRkdTailList = 成品入库体赋值(StrBodyName, id, z_任务单实际投入List);
            //塞入临时表

            Strsql = new StringBuilder();
            Strsql.Append("select editprop='A',* from " + StrHeadName);
            DOMDocument domHead = Pub.getDom(Strsql.ToString(), u8Login.UfDbName);
            Strsql = new StringBuilder();
            Strsql.Append("select editprop='A',* from " + StrBodyName);
            DOMDocument domBody = Pub.getDom(Strsql.ToString(), u8Login.UfDbName);

            Strsql = new StringBuilder();
            Strsql.Append(" if not object_id('" + StrHeadName + "') is null drop table " + StrHeadName);
            Strsql.Append(" if not object_id('" + StrBodyName + "') is null drop table " + StrBodyName);

            DbHelperSQL.ExecuteSql(Strsql.ToString());

            broker.AssignNormalValue("DomHead", domHead);
            //方法一是直接传入MSXML2.DOMDocumentClass对象
            broker.AssignNormalValue("domBody", domBody);


            //给普通参数domPosition赋值。此参数的数据类型为System.Object，此参数按引用传递，表示货位：传空
            broker.AssignNormalValue("domPosition", null);

            //该参数errMsg为OUT型参数，由于其数据类型为System.String，为一般值类型，因此不必传入一个参数变量。在API调用返回时，可以通过GetResult("errMsg")获取其值

            //给普通参数cnnFrom赋值。此参数的数据类型为ADODB.Connection，此参数按引用传递，表示连接对象,如果由调用方控制事务，则需要设置此连接对象，否则传空
            broker.AssignNormalValue("cnnFrom", null);

            //该参数VouchId为INOUT型普通参数。此参数的数据类型为System.String，此参数按值传递。在API调用返回时，可以通过GetResult("VouchId")获取其值
            string VouchId = "";
            broker.AssignNormalValue("VouchId", VouchId);

            //该参数domMsg为OUT型参数，由于其数据类型为MSXML2.IXMLDOMDocument2，非一般值类型，因此必须传入一个参数变量。在API调用返回时，可以直接使用该参数
            MSXML2.DOMDocument domMsg = new MSXML2.DOMDocument();
            broker.AssignNormalValue("domMsg", domMsg);

            //给普通参数bCheck赋值。此参数的数据类型为System.Boolean，此参数按值传递，表示是否控制可用量。
            broker.AssignNormalValue("bCheck", false);

            //给普通参数bBeforCheckStock赋值。此参数的数据类型为System.Boolean，此参数按值传递，表示检查可用量
            broker.AssignNormalValue("bBeforCheckStock", false);

            //给普通参数bIsRedVouch赋值。此参数的数据类型为System.Boolean，此参数按值传递，表示是否红字单据
            broker.AssignNormalValue("bIsRedVouch", false);

            //给普通参数sAddedState赋值。此参数的数据类型为System.String，此参数按值传递，表示传空字符串
            broker.AssignNormalValue("sAddedState", "");

            //给普通参数bReMote赋值。此参数的数据类型为System.Boolean，此参数按值传递，表示是否远程：转入false
            broker.AssignNormalValue("bReMote", false);



            //第六步：调用API
            if (!broker.Invoke())
            {
                //错误处理
                Exception apiEx = broker.GetException();
                if (apiEx != null)
                {
                    if (apiEx is MomSysException)
                    {
                        MomSysException sysEx = apiEx as MomSysException;
                        材料出库单接口返回result = ("系统异常：" + sysEx.Message);
                        //todo:异常处理
                    }
                    else if (apiEx is MomBizException)
                    {
                        MomBizException bizEx = apiEx as MomBizException;
                        材料出库单接口返回result = ("API异常：" + bizEx.Message);
                        //todo:异常处理
                    }
                    //异常原因
                    String exReason = broker.GetExceptionString();
                    if (exReason.Length != 0)
                    {
                        材料出库单接口返回result = ("异常原因：" + exReason);
                    }
                }
                //结束本次调用，释放API资源
                broker.Release();
            }

            //第七步：获取返回结果

            //获取返回值
            //获取普通返回值。此返回值数据类型为System.String，此参数按值传递，表示错误描述：空，正确；非空，错误
            //System.String result = broker.GetReturnValue() as System.String;
            //材料出库单接口返回result = result;
            //获取普通OUT参数curID。此返回值数据类型为string，在使用该参数之前，请判断是否为空
            //string curIDRet = broker.GetResult("curID") as string;
            //获取普通OUT参数CurDom。此返回值数据类型为MSXML2.IXMLDOMDocument2，在使用该参数之前，请判断是否为空
            //MSXML2.IXMLDOMDocument2 CurDomRet = Convert.ToObject(broker.GetResult("CurDom"));
            //到货单接口返回result += JsonConvert.SerializeObject(broker.GetResult("CurDom"));


            //获取返回值
            //获取普通返回值。此返回值数据类型为System.Boolean，此参数按值传递，表示返回值:true:成功,false:失败
            System.Boolean result = Convert.ToBoolean(broker.GetReturnValue());

            //获取out/inout参数值

            //获取普通OUT参数errMsg。此返回值数据类型为System.String，在使用该参数之前，请判断是否为空
            System.String errMsgRet = broker.GetResult("errMsg") as System.String;
            材料出库单接口返回result = errMsgRet;
            //获取普通INOUT参数VouchId。此返回值数据类型为System.String，在使用该参数之前，请判断是否为空
            System.String VouchIdRet = broker.GetResult("VouchId") as System.String;
            rdrecord11Id = VouchIdRet;
            //获取普通OUT参数domMsg。此返回值数据类型为MSXML2.IXMLDOMDocument2，在使用该参数之前，请判断是否为空
            //MSXML2.IXMLDOMDocument2 domMsgRet = Convert.ToObject(broker.GetResult("domMsg"));

            //材料出库单接口返回result += JsonConvert.SerializeObject(broker.GetResult("domMsg"));
            //结束本次调用，释放API资源
            broker.Release();
            return result;

        }

        private static int 成品入库头赋值(string strHeadName, int id, List<Z_任务单实际产出> z_任务单实际产出)
        {
            Warehouse warehouse = SqlSugarHelp.scope.Queryable<Warehouse>().Where(it => it.cWhCode == z_任务单实际产出[0].仓库编号).First();
            recordinq recordinq = new recordinq();
            recordinq.id = id;
            //收发标志 
            recordinq.brdflag = 1;
            recordinq.cvouchtype = "10";
            recordinq.csysbarcode = "||st10|0000000002";
            recordinq.cwhcode = warehouse.cWhCode;
            if (z_任务单实际产出[0].统货分拣 == "统货分拣" )
            {
                recordinq.ddate = DateTime.Now;
            }
            else if (z_任务单实际产出[0].统货分拣 == "改包")
            {
                recordinq.ddate = DateTime.Now;
                //recordinq.ddate = new DateTime(2025,1,28);
            }
            else if (z_任务单实际产出[0].仓库编号 == "0308")
            {
                recordinq.ddate = DateTime.Now;
            }
            else {
                recordinq.ddate = (DateTime)z_任务单实际产出[0].质检时间;
                //recordinq.ddate = (DateTime)z_任务单实际产出[0].入库日期;
            }
            recordinq.ddate = (DateTime)z_任务单实际产出[0].入库日期;


            recordinq.ccode = getMaxCode();
            recordinq.crdcode = z_任务单实际产出[0].入库类别;
            recordinq.cdepcode = "06";//
            //recordinq.cpersoncode = "NULL";
            //recordinq.cprobatch = "NULL";
            //recordinq.chandler = "何雨";
            //recordinq.cmemo = "NULL";
            //recordinq.caccounter = "NULL";
            recordinq.cmaker = "何雨";
            //recordinq.cdefine1 = "NULL";
            //recordinq.cdefine2 = "NULL";
            //recordinq.cdefine3 = "NULL";
            //recordinq.cdefine4 = "NULL";
            //recordinq.cdefine5 = "NULL";
            //recordinq.cdefine6 = "NULL";
            //recordinq.cdefine7 = "NULL";
            //recordinq.cdefine8 = "NULL";
            //recordinq.cdefine9 = "NULL";
            //recordinq.cdefine10 = "NULL";
            recordinq.cwhname = warehouse.cWhName;
            //recordinq.cdepname = "NULL";
            //recordinq.cpersonname = "NULL";
            //recordinq.crdname = "NULL";
            recordinq.csource = "库存";
            recordinq.cbustype = "成品入库";
            //recordinq.dveridate = "2024-12-01 00:00:00.000";
            //recordinq.cbuscode = "NULL";
            //recordinq.cptcode = "NULL";
            //recordinq.cstcode = "NULL";
            //recordinq.ccuscode = "NULL";
            //recordinq.cvencode = "NULL";
            //recordinq.cordercode = "NULL";
            //recordinq.carvcode = "NULL";
            //recordinq.cbillcode = "NULL";
            //recordinq.cdlcode = "NULL";
            //recordinq.darvdate = "NULL";
            //recordinq.cchkcode = "NULL";
            //recordinq.dchkdate = "NULL";
            //recordinq.cchkperson = "NULL";
            recordinq.vt_id = 63;
            recordinq.bisstqc = false;
            //recordinq.cdefine11 = "NULL";
            //recordinq.cdefine12 = "NULL";
            //recordinq.cdefine13 = "NULL";
            //recordinq.cdefine14 = "NULL";
            //recordinq.cdefine15 = "NULL";
            //recordinq.cdefine16 = "NULL";
            //recordinq.imquantity = "NULL";
            //recordinq.cmpocode = "NULL";
            recordinq.bpufirst = false;
            recordinq.biafirst = false;
            //recordinq.ipurorderid = "NULL";
            recordinq.iproorderid = 0;
            recordinq.ireturncount = 0;
            recordinq.iverifystate = 0;
            recordinq.iswfcontrolled = 0;
            recordinq.ufts = "                      466.4531";
            recordinq.cmodifyperson = "";
            //recordinq.dmodifydate = "NULL";
            recordinq.dnmaketime = DateTime.Now;
            //recordinq.dnmodifytime = "NULL";
            //recordinq.dnverifytime = "2024-11-25 15:59:04.603";
            recordinq.bomfirst = 0;
            recordinq.chinvsn = "";
            //recordinq.iflowid = "NULL";
            //recordinq.cflowname = "NULL";
            recordinq.iPrintCount = 0;
            //recordinq.ccurrentauditor = "NULL";
            //recordinq.outid = "NULL";
            //recordinq.cfactorycode = "NULL";
            //recordinq.cfactoryname = "NULL";
            //recordinq.cchecksignflag = "F5E1E8F298E53CB979A7F798C4C8E319";

            return recordinq.Add(strHeadName);
        }

        private static int 成品入库体赋值(string strBodyName, int id, List<Z_任务单实际产出> z_任务单实际产出List)
        {
            foreach (var z_任务单实际产出 in z_任务单实际产出List)
            { 
            
           
                Inventory inventory = SqlSugarHelp.scope.Queryable<Inventory>().Where(it => it.cInvCode == z_任务单实际产出.产出物料编号).First();
                int autoid = (int)SnowFlakeSingle.Instance.NextId();
                recordinsq recordinsq = new recordinsq();
                recordinsq.autoid = autoid;
                recordinsq.id = id;
                recordinsq.cinvcode = inventory.cInvCode;
                recordinsq.cinvaddcode = inventory.cInvAddCode;
                recordinsq.cinvname = inventory.cInvName;
            recordinsq.cinvstd = inventory.cInvStd;
            recordinsq.cinvccode = inventory.cInvCCode;
            recordinsq.cinvm_unit = inventory.cComUnitCode;
                //recordinsq.cinva_unit = "NULL";
                //recordinsq.creplaceitem = "NULL";
                //recordinsq.cposition = "NULL";
                //recordinsq.cinvdefine1 = z_任务单实际产出;
                //recordinsq.cinvdefine2 = "NULL";
                //recordinsq.cinvdefine3 = "NULL";
                //recordinsq.cinvdefine4 = "NULL";
                //recordinsq.cinvdefine5 = "NULL";
                //recordinsq.cinvdefine6 = "NULL";
                //recordinsq.cinvdefine7 = "NULL";
                //recordinsq.cinvdefine8 = "NULL";
                //recordinsq.cinvdefine9 = "NULL";
                //recordinsq.cinvdefine10 = "NULL";
                //recordinsq.cinvdefine11 = "NULL";
                //recordinsq.cinvdefine12 = "NULL";
                //recordinsq.cinvdefine13 = "NULL";
                //recordinsq.cinvdefine14 = "NULL";
                //recordinsq.cinvdefine15 = "NULL";
                //recordinsq.cinvdefine16 = "NULL";
                //recordinsq.iid = "NULL";
                //if (string.IsNullOrWhiteSpace(z_任务单实际产出.统货拣货次数) == false)
                //{
                //    recordinsq.cfree1 = z_任务单实际产出.统货拣货次数;
                //}
                if (是否启用存货自由项统货拣货次数(inventory.cInvCode))
                {
                    recordinsq.cfree1 = z_任务单实际产出.统货拣货次数;
                }
                //recordinsq.cfree1 = "NULL";
                if (是否启用存货自由项等级说明(inventory.cInvCode))
                {
                    recordinsq.cfree2 = z_任务单实际产出.等级说明;
                }
                
                //recordinsq.cfree3 = "NULL";
                //recordinsq.cfree4 = "NULL";
                //recordinsq.cfree5 = "NULL";
                //recordinsq.cfree6 = "NULL";
                //recordinsq.cfree7 = "NULL";
                //recordinsq.cfree8 = "NULL";
                //recordinsq.cfree9 = "NULL";
                //recordinsq.cfree10 = "NULL";
                if (inventory.bInvBatch == true)
                {
                    recordinsq.cbatch = z_任务单实际产出.本厂批号;
                }
               
                //recordinsq.inquantity = z_任务单实际产出.入库数量;
                //recordinsq.innum = "NULL";
                //recordinsq.cassunit = "NULL";
                recordinsq.dmadedate = z_任务单实际产出.生产日期;
                //recordinsq.cbarcode = "NULL";
                //recordinsq.iinvexchrate = "NULL";
                //recordinsq.inum = "NULL";
                recordinsq.iquantity = z_任务单实际产出.入库数量;
                if (z_任务单实际产出.产出物料名称 == "冬虫夏草")
                {
                    recordinsq.iunitcost = z_任务单实际产出.入库单价.GetValueOrDefault();
                   recordinsq.iprice = z_任务单实际产出.入库金额;
                }
                //recordinsq.iunitcost = "NULL";
                //recordinsq.iprice = "NULL";
                //recordinsq.ipunitcost = "NULL";
                //recordinsq.ipprice = "NULL";
                //recordinsq.dvdate = "NULL";
                //recordinsq.isoutquantity = "NULL";
                //recordinsq.isoutnum = "NULL";
                //recordinsq.ifquantity = "NULL";
                //recordinsq.ifnum = "NULL";
                //recordinsq.cvouchcode = "NULL";
                recordinsq.cdefine22 = z_任务单实际产出.任务单号;
                recordinsq.cdefine23 = z_任务单实际产出.实际产出guid.ToString();
                //recordinsq.cdefine24 = "NULL";
                //recordinsq.cdefine25 = "NULL";
                //recordinsq.cdefine26 = "NULL";
                //recordinsq.cdefine27 = "NULL";
                //recordinsq.cdefine28 = "NULL";
                //recordinsq.cdefine29 = "NULL";
                //recordinsq.cdefine30 = "NULL";
                //recordinsq.cdefine31 = "NULL";
                //recordinsq.cdefine32 = "NULL";
                //recordinsq.cdefine33 = "NULL";
                //recordinsq.cdefine34 = "NULL";
                //recordinsq.cdefine35 = "NULL";
                //recordinsq.cdefine36 = "NULL";
                //recordinsq.cdefine37 = "NULL";
                //recordinsq.impoids = "NULL";
                //recordinsq.icheckids = "NULL";
                //recordinsq.citemcode = "NULL";
                //recordinsq.citem_class = "NULL";
                //recordinsq.cname = "NULL";
                //recordinsq.cinvouchcode = "NULL";
                //recordinsq.citemcname = "NULL";
                //recordinsq.cbvencode = "NULL";
                //recordinsq.cvenname = "NULL";
                //recordinsq.imassdate = "NULL";
                //recordinsq.cposname = "NULL";
                //recordinsq.ccheckcode = "NULL";
                //recordinsq.icheckidbaks = "NULL";
                //recordinsq.crejectcode = "NULL";
                //recordinsq.irejectids = "NULL";
                //recordinsq.ccheckpersoncode = "NULL";
                //recordinsq.dcheckdate = "NULL";
                recordinsq.brelated = false;
                //recordinsq.cmassunit = "NULL";
                //recordinsq.cmocode = "NULL";
                //recordinsq.imoseq = "NULL";
                //recordinsq.iopseq = "NULL";
                //recordinsq.copdesc = "NULL";
                //recordinsq.cmolotcode = "NULL";
                //recordinsq.cmworkcentercode = "NULL";
                //recordinsq.cmworkcenter = "NULL";
                recordinsq.corufts = "";
                //recordinsq.ccheckpersonname = "NULL";
                //recordinsq.isodid = "NULL";
                recordinsq.isotype = 0;
                //recordinsq.csocode = "NULL";
                //recordinsq.isoseq = "NULL";
                recordinsq.cdemandmemo = "";
                recordinsq.iordertype = 0;
                //recordinsq.iorderdid = "NULL";
                //recordinsq.iordercode = "NULL";
                //recordinsq.iorderseq = "NULL";
                //recordinsq.cbaccounter = "NULL";
                recordinsq.bcosting = true;
                //recordinsq.dbkeepdate = "NULL";
                //recordinsq.cvmivencode = "NULL";
                //recordinsq.cvmivenname = "NULL";
                recordinsq.bvmiused = false;
                //recordinsq.ivmisettlequantity = "NULL";
                //recordinsq.ivmisettlenum = "NULL";
                //recordinsq.iinvsncount = "NULL";
                //recordinsq.iuninvsncount = "NULL";
                recordinsq.iexpiratdatecalcu = 0;
                recordinsq.cexpirationdate = z_任务单实际产出.有效日期?.ToString("yyyy-MM-dd");
                //recordinsq.dexpirationdate = "NULL";
                //recordinsq.cciqbookcode = "NULL";
                //recordinsq.ibondedsumqty = "NULL";
                //recordinsq.cbatchproperty1 = "NULL";
                //recordinsq.cbatchproperty2 = "NULL";
                //recordinsq.cbatchproperty3 = "NULL";
                //recordinsq.cbatchproperty4 = "NULL";
                //recordinsq.cbatchproperty5 = "NULL";
                //recordinsq.cbatchproperty6 = "NULL";
                //recordinsq.cbatchproperty7 = "NULL";
                //recordinsq.cbatchproperty8 = "NULL";
                //recordinsq.cbatchproperty9 = "NULL";
                //recordinsq.cbatchproperty10 = "NULL";
                //recordinsq.productinids = "NULL";
                recordinsq.cbmemo = z_任务单实际产出.入库备注;
                recordinsq.cbinvsn = "";
                recordinsq.irowno = 1;
                //recordinsq.strowguid = "NULL";
                //recordinsq.iposflag = "NULL";
                //recordinsq.vmiveniid = "NULL";
                //recordinsq.cservicecode = "NULL";
                //recordinsq.bveniid = "NULL";
                //recordinsq.cinvouchtype = "NULL";
                //recordinsq.cbsysbarcode = "||st10|0000000002|1";
                //recordinsq.cplanlotcode = "NULL";
                recordinsq.bmergecheck = false;
                //recordinsq.imergecheckautoid = "NULL";
                //recordinsq.iorderdetailid = "NULL";
                //recordinsq.body_outid = "NULL";


                recordinsq.Add(strBodyName);
            }
            return 1;
        }

        private static string getMaxCode()
        {
            string sql = @"select  isnull(max(right(cCode,4)),'0000') from RecordInQ
						-- where DATEDIFF(MONTH,dDate ,GETDATE()) = 0";
            int code = SqlSugarHelp.scope.Ado.GetInt(sql);
            code++;
            return code.ToString().PadLeft(8, '0');
        }

        public static bool 是否启用存货自由项统货拣货次数(string 物料编号)
        {
            Inventory inventory = SqlSugarHelp.scope.Queryable<Inventory>().Where(it => it.cInvCode == 物料编号).First();
            return inventory.bFree1;

            //List<AA_InvFreeContrapose> AA_InvFreeContraposeList = SqlSugarHelp.scope.Queryable<AA_InvFreeContrapose>()
            //                                                                  .Where(it => it.cInvCode == 物料编号
            //                                                                   && it.cUDID == "20").ToList();
            //if (AA_InvFreeContraposeList != null && AA_InvFreeContraposeList.Count > 0)
            //{
            //    return true;
            //}
            //else
            //{
            //    return false;
            //}
        }

        public static List<AA_InvFreeContrapose> 获取所有自由项统货拣货次数(string 物料编号)
        {
            List<AA_InvFreeContrapose> AA_InvFreeContraposeList = SqlSugarHelp.scope.Queryable<AA_InvFreeContrapose>()
                                                                              .Where(it => it.cInvCode == 物料编号
                                                                               && it.cUDID == "20").ToList();
            return AA_InvFreeContraposeList;
        }

        public static bool 是否启用存货自由项等级说明(string 物料编号)
        {
            Inventory inventory = SqlSugarHelp.scope.Queryable<Inventory>().Where(it => it.cInvCode == 物料编号).First();
            return inventory.bFree2;
            //List<AA_InvFreeContrapose> AA_InvFreeContraposeList = SqlSugarHelp.scope.Queryable<AA_InvFreeContrapose>()
            //                                                                  .Where(it => it.cInvCode == 物料编号
            //                                                                   && it.cUDID == "21").ToList();
            //if (AA_InvFreeContraposeList != null && AA_InvFreeContraposeList.Count > 0)
            //{
            //    return true;
            //}
            //else
            //{
            //    return false;
            //}
        }
    }
}